using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class BagCell : MonoBehaviour, IDragHandler, IEndDragHandler, IBeginDragHandler,IPointerClickHandler
{
    public BagModel currModel;
    public Image goods;
    public Text num;
    BagModel startData;
    BagModel endData;
    public void SetSprite(string spriteName = null)
    {
        if (spriteName == null)
        {
            goods.GetComponent<Image>().sprite = Resources.Load<Sprite>("Icon1/PP");
        }
        else
        {
            goods.GetComponent<Image>().sprite = Resources.Load<Sprite>("Icon1/" + spriteName);
        }
    }
    public void Init(BagModel model = null)
    {
        if (model == null)
        {
            SetSprite();
            num.text = "";
        }
        else
        {
            currModel = model;
            SetSprite(model.Id.ToString());
            num.text = model.Num.ToString();
        }
    }
    GameObject tempLate;
    public void OnBeginDrag(PointerEventData eventData)
    {
        Debug.Log(eventData.pointerEnter.name);
        SetSprite();
        num.text = "";
        tempLate = GameObjectUtility.Instance.CreateGameObject("_Prefabs/BagItem", transform.parent);
        tempLate.GetComponent<Image>().raycastTarget = false;
        tempLate.GetComponent<BagCell>().Init(currModel);
        tempLate.transform.position = Input.mousePosition;
        startData = currModel;
        currModel = null;
    }

    public void OnDrag(PointerEventData eventData)
    {
        if (tempLate != null)
        {
            tempLate.transform.position = Input.mousePosition;
        }
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        if(eventData.pointerEnter==null || eventData.pointerEnter.GetComponent<BagCell>().currModel == null)
        {
            Init(startData);
            Destroy(tempLate);
            return;
        }
        endData = eventData.pointerEnter.GetComponent<BagCell>().currModel;
        if (endData == null)
        {
            eventData.pointerEnter.GetComponent<BagCell>().Init(startData);
            Init();
        }
        else
        {
            eventData.pointerEnter.GetComponent<BagCell>().Init(startData);
            Init(endData);
        }
        Destroy(tempLate);
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        
    }
}
